package name.sakanacatcher.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.ObjectBuffer;
import name.sakanacatcher.entity.Group;
import name.sakanacatcher.entity.User;
import name.sakanacatcher.service.AuthService;
import name.sakanacatcher.service.InformService;
import name.sakanacatcher.service.UserService;
import name.sakanacatcher.util.ResultUtil;
import name.sakanacatcher.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    TokenUtil tokenUtil;

    @Autowired
    ResultUtil resultUtil;

    @Autowired
    InformService informService;

    @Autowired
    AuthService authService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @GetMapping("/check/username")
    public Map<String, Object> checkUsername(@RequestParam String username){
        return resultUtil.successResult("Get Success", userService.getUserRepository().existsByUsername(username));
    }
    @GetMapping("/check/com")
    public Map<String, Object> checkUserCom(@RequestParam String username){
        return resultUtil.successResult("Get Success", userService.getUserRepository().getByUsername(username).getCom() != null);
    }

    @PostMapping("/update/role/hr")
    public Map<String, Object> addHrToCom(@RequestBody Map<String,Object> data){
        return resultUtil.successResult("Get Success", userService.addHrToCom(data));
    }

    @PostMapping("/delete/role/hr")
    public Map<String, Object> deleteHrToCom(@RequestBody Map<String,Object> data){
        return resultUtil.successResult("Get Success", userService.deleteHrToCom(data));
    }

    @GetMapping("/info")
    public Map<String, Object> getInfo(@RequestHeader("Authorization") String authorization) {
        String username = tokenUtil.getSubject(authorization.replace("Bearer ", ""));
        Map<String, Object> info = userService.getInfoByUsername(username);

        return resultUtil.successResult("Get Success", info);
    }
    @GetMapping("/detail")
    public Map<String, Object> getInfoDetail(@RequestParam("id") int id) {
        if(userService.getUserRepository().existsById(id)){
            return resultUtil.successResult("Get Success",Map.of("items", userService.getUserRepository().getById(id)));
        }
        else {
            return resultUtil.customResult(500,"找不到该用户");
        }
    }
    @PostMapping("/register")
    public Map<String, Object> registerUser(@RequestBody Map<String,Object> data) {
        if(userService.registerUser(data)){
            return resultUtil.successResult("Get Success", "注册成功");
        }
        else{
            return resultUtil.customResult(500,"未知的错误");
        }
    }

    @GetMapping("/list/cid")
    public Map<String, Object> getHrList(
            @RequestParam int cid,
            @RequestParam int page,
            @RequestParam int limit
    ) {
        Pageable pageable = PageRequest.of(page, limit);
        List<User> users = userService.getUsersByCid(cid);
        int total = users.size();
        int totalPage = (int)Math.ceil(total / (double)limit);
        if(page <= totalPage && page >= 1){
            if(page * limit > total){
                users = users.subList((page - 1)*limit, total);
            }
            else {
                users = users.subList((page - 1)*limit,page * limit);
            }
        }
        else{
            users = users.subList(0,0);
        }
        return resultUtil.successResult("Get Success", Map.of("items", users, "total",total));
    }

    @GetMapping("/list")
    public Map<String, Object> getTable(@RequestParam(name = "page", required = true) int page,
                                        @RequestParam(name = "limit", required = true) int limit,
                                        @RequestParam(name = "type", required = false) String type,
                                        @RequestParam(name = "title", required = false) String title,
                                        @RequestParam(name = "status", required = false) boolean status) throws JsonProcessingException {
       List<User> table = userService.getUserRepository().findAll();
        // 条件筛选
        table =  table.stream().filter(
                item ->{
                    ObjectMapper mapper = new ObjectMapper();
                    try {
                        String json = mapper.writeValueAsString(item); //将对象转换成json
                        JSONObject m = JSONObject.parseObject(json);
                        boolean flag = true;
                        boolean statusFlag = true;
                        if (title != null && !title.equals("")) {
                            flag = false;
                            if (type != null && !type.equals("")) {
                                if(type.equals("id"))
                                    flag = m.get("id").equals(Integer.parseInt(title));
                                else
                                    flag = ((String)m.get(type)).contains(title);
                            } else {
                                flag = ((String)m.get("name") != null && ((String)m.get("name")).contains(title));
                            }
                        }


                        return flag;
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
        ).collect(Collectors.toList());
        int total = table.size();
        int totalPage = (int)Math.ceil(total / (double)limit);
        if(page <= totalPage && page >= 1){
            if(page * limit > total){
                table = table.subList((page - 1)*limit, total);
            }
            else {
                table = table.subList((page - 1)*limit,page * limit);
            }
        }
        return resultUtil.successResult("Get Success", Map.of("items", table ,"total",total));
    }

    @PostMapping("/resetPassword")
    public Map<String, Object> resetPassword(@RequestBody Map<String,Object> data) {
        String reqUsername = SecurityContextHolder.getContext().getAuthentication().getName();
        User reqUser = userService.getUserRepository().getByUsername(reqUsername);
        if(reqUser.getId() != (int)data.get("id")) {
            return  resultUtil.customResult(402,"你没有权限进行次操作");
        }
        else{
            User user = userService.getUserRepository().getById((int)data.get("id"));
            String encrypt = passwordEncoder.encode((String)data.get("password"));
            user.setPassword(encrypt);
            System.out.println(user);
            userService.getUserRepository().save(user);
            return resultUtil.successResult("reset Success");
        }
    }
    @PostMapping("update/info")
    public Map<String, Object> updateBasicInfo(@RequestBody Map<String,Object> data) {
        if(userService.updateBasicInfo(data)){
            return resultUtil.successResult("修改用户信息");
        }
        else
            return  resultUtil.customResult(500,"未知的错误");
    }

    @PostMapping("/update/avatar")
    public Map<String, Object> updateAvatar(@RequestBody Map<String,Object> data) {
        if(userService.updateAvatar(data)){
            return resultUtil.successResult("修改头像成功");
        }
        else {
            return  resultUtil.customResult(500,"未知的错误");
        }
    }

}
